package org.totoro.concurrent.juc.lock;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁
 *
 * @author daocr
 * @date 2019-06-03
 */
public class ReentrantLockTest {


    public static void main(String[] args) throws InterruptedException {

        ReentrantLock reentrantLock = new ReentrantLock();


        AtomicReference<Thread> thread = new AtomicReference<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {

                if (reentrantLock.tryLock()) {

                    try {

                        System.out.println(Thread.currentThread().getName() + "获取锁成功");

                        thread.set(Thread.currentThread());

                        Thread.sleep(1000000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        reentrantLock.unlock();
                    }

                    return;
                }

                System.out.println(Thread.currentThread().getName() + "获取锁失败");


            }).start();
        }

        Thread.sleep(5000);

        thread.get().interrupt();


    }

}
